package com.commerce.recording.activity;

import android.content.ContentValues;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.os.StrictMode;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.SearchView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import com.commerce.recording.R;
import com.commerce.recording.Singleton;
import com.commerce.recording.adapter.MyAllAdapter;
import com.commerce.recording.entity.Record;
import com.commerce.recording.entity.Sign;
import com.commerce.recording.utils.Delete;
import com.commerce.recording.utils.ShareManager;

import org.litepal.LitePal;

import java.io.File;
import java.io.Serializable;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class SeeActivity extends AppCompatActivity {

    private SearchView seeSvSearch;
    private Button mMenuDelete;
    private Button mMenuRename;
    private Button mMenuSend;
    private Button mMenuCancel;
    private LinearLayout mLlSeeMenu;
    private final List<Record> allRecord = new ArrayList<>();
    private MyAllAdapter myAllAdapter;
    private Map<String, List<Sign>> signsMap;
    private TextView seeTvBack;
    private ListView seeLvRecord;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_see);
        //从Android 7.0开始，google修改了数据传递，一个应用提供自身文件给其它应用使用时，
        // 如果给出一个file://格式的URI的话，应用会抛出FileUriExposedException。
        // 这是由于谷歌认为目标app可能不具有文件权限，会造成潜在的问题。所以会报错。
        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.N){
            StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
            StrictMode.setVmPolicy(builder.build());
            builder.detectFileUriExposure();
        }
        initViews();

    }

    /**
     * 初始化
     */
    private void initViews() {
        seeTvBack = findViewById(R.id.see_tv_back);
        seeLvRecord = findViewById(R.id.see_lv_record);
        seeSvSearch = findViewById(R.id.see_sv_search);
        seeSvSearch.setIconifiedByDefault(false);
        setUnderLinetransparent(seeSvSearch);
        lookup("");
        signsMap = new HashMap<>();
        for (Record record : allRecord) {
            String path = record.getPath();
            List<Sign> signs = LitePal.where("pathId = ? ", path).find(Sign.class);
            signsMap.put(path, signs);
        }
        myAllAdapter = new MyAllAdapter(allRecord, signsMap);
        seeLvRecord.setAdapter(myAllAdapter);
        seeSvSearch.setImeOptions(3);
        seeSvSearch.setSubmitButtonEnabled(true);
        seeSvSearch.setQueryHint("搜索录音");
        mMenuDelete = findViewById(R.id.menu_delete);
        mMenuRename = findViewById(R.id.menu_rename);
        mMenuSend = findViewById(R.id.menu_send);
        mMenuCancel = findViewById(R.id.menu_cancel);
        mLlSeeMenu = findViewById(R.id.ll_see_menu);
        click();
    }

    /**
     * 监听事件
     */
    private void click() {
        seeTvBack.setOnClickListener(v -> finish());
        //删除
        mMenuDelete.setOnClickListener(v -> {
            List<File> fileList = new ArrayList<>();
            for (Record record : Singleton.getInstance().getCheckRecord()){
                fileList.add(new File(record.getPath()));
                LitePal.delete(Record.class,record.getId());
                Delete.delete(record.getPath());
            }
            close();
        });
        //重命名
        mMenuRename.setOnClickListener(v -> {
            /*@setView 装入一个EditView
                 */
            final EditText editText = new EditText(SeeActivity.this);
            AlertDialog.Builder inputDialog = new AlertDialog.Builder(SeeActivity.this);
            inputDialog.setTitle("重命名").setView(editText);
            inputDialog.setCancelable(false);
            inputDialog.setPositiveButton("确定", (dialog, which) ->{
                    if(editText.getText().length()>0){
                        Record record = Singleton.getInstance().getCheckRecord().get(0);
                        ContentValues contentValues = new ContentValues();
                        contentValues.put("name",editText.getText().toString().trim());
                        contentValues.put("time",record.getTime());
                        contentValues.put("path",record.getPath());
                        contentValues.put("check","false");
                        LitePal.update(Record.class,contentValues,record.getId());
                        close();
                    }
                    }).show();
        });
        //分享事件
        mMenuSend.setOnClickListener(v -> {
            List<File> fileList = new ArrayList<>();
            for (Record record : Singleton.getInstance().getCheckRecord()){
                File file = new File(record.getPath());
                if(file.exists()){
                    fileList.add(file);
                }
            }
            ShareManager.shareFiles(SeeActivity.this,fileList);
        });
        mMenuCancel.setOnClickListener(v ->close());
        //搜索框文字监听
        seeSvSearch.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            //提交
            public boolean onQueryTextSubmit(String query) {
                lookup(query);
                seeSvSearch.clearFocus();  //可以收起键盘
                return true;
            }

            @Override
            //文字改变
            public boolean onQueryTextChange(String newText) {
                if (newText.length() == 0) {
                    lookup("");
                }
                return true;
            }
        });
        seeLvRecord.setOnItemClickListener((parent, view, position, id) -> {
            Log.d("TAG", "onItemClick: " +Singleton.getInstance().isCheck());
            if(Singleton.getInstance().isCheck()){
                Record record = allRecord.get((int) id);
                record.setCheck(!record.isCheck());
                if(record.isCheck()){
                    Singleton.getInstance().addCheckRecord(record);
                }else {
                    Singleton.getInstance().removeCheckRecord(record);
                }
                //重命名是否启用
                mMenuRename.setEnabled(Singleton.getInstance().getCheckRecord().size()==1);
                //发送是否启用
                mMenuSend.setEnabled(0<Singleton.getInstance().getCheckRecord().size());
                mMenuDelete.setEnabled(0<Singleton.getInstance().getCheckRecord().size());
                myAllAdapter.notifyDataSetChanged();
            }else {
                String path = allRecord.get((int) id).getPath();
                String name = allRecord.get((int) id).getName();
                List<Sign> signs = signsMap.get(path);
                Intent intent = new Intent(SeeActivity.this, PlayActivity.class);
                intent.putExtra("signs", (Serializable) signs);
                intent.putExtra("path", path);
                intent.putExtra("name", name);
                startActivity(intent);
            }
        });
        seeLvRecord.setOnItemLongClickListener((parent, view, position, id) -> {
            allRecord.get((int) id).setCheck(true);
            Singleton.getInstance().setCheck(true);
            Singleton.getInstance().addCheckRecord(allRecord.get((int) id));
            mLlSeeMenu.setVisibility(View.VISIBLE);
            return true;
        });
    }


    /**
     * 搜索功能
     * @param query 关键字
     */
    private void lookup(String query) {
        allRecord.clear();
        for (Record record : LitePal.findAll(Record.class)) {
            if (record.getName().contains(query)) {
                allRecord.add(record);
            }
        }
        if (myAllAdapter != null) {
            myAllAdapter.notifyDataSetChanged();
        }
    }

    /**
     * 设置下划线透明
     **/
    private void setUnderLinetransparent(SearchView searchView) {
        try {
            //利用对象调用getClass()方法获取该对象的Class实例；
            Class<?> argClass = searchView.getClass();
            // mSearchPlate是SearchView父布局的名字，说白了就是获取一个类的成员变量
            Field ownFieldSearch = argClass.getDeclaredField("mSearchPlate");
            Field ownFieldSubmit = argClass.getDeclaredField("mSubmitArea");
            //表示反射对象在使用时禁止Java语言访问检查 ，取消了Java的权限控制检查（会破坏类的访问规则，产生安全隐患）。
            //而且JDK的安全检查耗时较多，所以通过setAccessible(true)的方式关闭安全检查来提升反射速度
            ownFieldSearch.setAccessible(true);
            ownFieldSubmit.setAccessible(true);
            //获取它的值
            View mViewSearch = (View) ownFieldSearch.get(searchView);
            View mViewSubmit = (View) ownFieldSubmit.get(searchView);
            //TRANSPARENT（透明色）
            mViewSearch.setBackgroundColor(Color.TRANSPARENT);
            mViewSubmit.setBackgroundColor(Color.TRANSPARENT);
        } catch (NoSuchFieldException | IllegalAccessException e) {
            e.printStackTrace();
        }
    }

    //关闭编辑模式
    private void close(){
        Singleton.getInstance().setCheck(false);
        Singleton.getInstance().clear();
        mLlSeeMenu.setVisibility(View.GONE);
        lookup("");
    }

    @Override
    protected void onPause() {
        close();
        super.onPause();
    }
}